﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.BomInfo;
using WPFServices.Services.DomainService.Productinfo;
using WPFServices.Views.DomainViews.BomInfo;

namespace WPFServices.ViewModels.DomainViewModel.Productinfo
{
    public class ProductViewModel:BaseViewModel
    {
        private readonly ProductService _productService;
        private ObservableCollection<ProductDto> _product;
        private ProductDto _selectedProduct; // 当前选中的产品
        private bool _isLoading; // 数据加载状态
        private int _currentPage = 1; // 当前页码
        private int _pageSize = 10; // 每页大小
        private int _totalCount; // 总记录数
        private int _totalPages; // 总页数

        public ProductViewModel()
        {
            _productService = new ProductService();
            _product = new ObservableCollection<ProductDto>();
            LoadDataCommand = new RelayCommand(async _ => await LoadProductAsync());
            SearchCommand = new RelayCommand(async _ => await SearchProductAsync());
            FirstPageCommand = new RelayCommand(_ => GoToFirstPage(), _ => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(_ => GoToPreviousPage(), _ => CurrentPage > 1);
            NextPageCommand = new RelayCommand(_ => GoToNextPage(), _ => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(_ => GoToLastPage(), _ => CurrentPage < TotalPages);
            SaveCommand = new RelayCommand(_ => Save(), _ => CanSave());
            CancelCommand = new RelayCommand(_ => Cancel());

            _ = LoadProductAsync();
        }

        #region 属性
        // 用于UI绑定的数据属性，通过SetProperty实现变更通知。
        public ObservableCollection<ProductDto> Products
        {
            get => _product;
            set => SetProperty(ref _product, value);
        }

        public ProductDto SelectedProduct
        {
            get => _selectedProduct;
            set => SetProperty(ref _selectedProduct, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }
        #endregion

        #region 命令
        // 用于UI绑定和触发ViewModel操作的命令。
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand SearchCommand { get; }
        public RelayCommand FirstPageCommand { get; }
        public RelayCommand PreviousPageCommand { get; }
        public RelayCommand NextPageCommand { get; }
        public RelayCommand LastPageCommand { get; }
        public RelayCommand SaveCommand { get; }
        public RelayCommand CancelCommand { get; }
        #endregion

        #region 事件
        public event Action<bool> CloseWindow;
        #endregion

        #region 方法
        // 加载产品数据，重置到第一页并触发搜索。
        private async Task LoadProductAsync()
        {
            CurrentPage = 1;
            await SearchProductAsync();
        }

        // 异步搜索产品数据，并更新分页信息。
        private async Task SearchProductAsync()
        {
            try
            {
                IsLoading = true;
                var searchDto = new SearchProductDto
                {
                    PageIndex = CurrentPage,
                    PageSize = PageSize
                };

                var result = await _productService.SearchProductAsync(searchDto);

                Products.Clear();
                if (result.Data != null)
                {
                    foreach (var product in result.Data)
                    {
                        Products.Add(product);
                    }
                }
                TotalCount = result.TotalCount;
                TotalPages = result.TotalPage;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"获取产品数据失败: {ex.Message}", "错误");
            }
            finally
            {
                IsLoading = false;
            }
        }

        // 跳转到第一页。
        private void GoToFirstPage()
        {
            CurrentPage = 1;
            _ = SearchProductAsync();
        }

        // 跳转到上一页。
        private void GoToPreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = SearchProductAsync();
            }
        }

        // 跳转到下一页。
        private void GoToNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = SearchProductAsync();
            }
        }

        // 跳转到最后一页。
        private void GoToLastPage()
        {
            CurrentPage = TotalPages;
            _ = SearchProductAsync();
        }

        // 检查是否可以保存
        private bool CanSave()
        {
            return SelectedProduct != null;
        }

        // 保存选中的产品
        private void Save()
        {
            if (SelectedProduct != null)
            {
                CloseWindow?.Invoke(true); // 返回true表示成功选择
            }
        }

        // 取消选择
        private void Cancel()
        {
            CloseWindow?.Invoke(false); // 返回false表示取消
        }
        #endregion
    }
}
